import { app, BrowserWindow, protocol, net } from "electron"
import path from "node:path"
import url from "node:url"

import { RegisterApi, CallApi } from "./api_routes.js"

const __dirname = path.dirname(url.fileURLToPath(import.meta.url))

let app_scheme = 'lxce';
let app_url = app_scheme + '://ux/index.html';
let app_protocol_handler = (request) => {
    const request_url = new URL(request.url)
    if (request_url.pathname.startsWith('/api/v1')) {
        return CallApi(request_url.pathname, request)
    } else {
        return net.fetch(url.pathToFileURL(path.join(__dirname, '../elpoc/dist', request_url.pathname.slice(1))).toString(), { bypassCustomProtocolHandlers: true })
    }
};
if (process.env.NODE_ENV === 'development') {
    app_scheme = 'http'
    app_url ='http://localhost:5173'
    app_protocol_handler = (request) => {
        const request_url = URL.parse(request.url)
        console.log("dev_url:" + request.url)
        if (request_url.pathname.startsWith('/api/v1')) {
            return CallApi(request_url.pathname, request)
        } else {
            return net.fetch(request.url, {
                method: request.method,
                headers: request.headers,
                body: request.body,
                bypassCustomProtocolHandlers: true,
            })
        }
    };
}

protocol.registerSchemesAsPrivileged([
    {
        scheme: app_scheme,
        privileges: {
            standard: true,
            secure: true,
            supportFetchAPI: true,
            bypassCSP: true,
            stream: true
        }
    }
])

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600
    })
    protocol.handle(app_scheme, app_protocol_handler)
    win.loadURL(app_url)
}


app.whenReady().then(() => {
    RegisterApi('/api/v1/hello', ['GET', 'POST'], async (request) => {
        console.log(request.method)
        if (request.method == 'GET') {
            console.log("get hello")
        } else {
            console.log("data: " + request.data)
        }
        return new Response('hello world', { headers: { 'Content-Type': 'text/text' } })
    })
    createWindow()
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})